<template>
  <view>
    <view>
      <view class="u-p-24 search u-flex ">
        <u-search @change="searchChange" shape="round" placeholder="请输入订单编号、商品名" :show-action="false"
                  class="u-flex-1 u-m-r-24" v-model.lazy="params.groupValue"></u-search>
        <view class="ri_btn u-flex u-col-center u-row-center" @click="show = !show">
          <image src="@/static/images/base/seleEnum.png" mode="widthFix"></image>
          <text>{{show?'收起':'筛选'}}</text>
        </view>

      </view>

      <view class="seleBottom"
            style="position: fixed;width: 100%;z-index: 10;border-bottom: 1 solid #242424;u-font-36"
            :style="{height:show?heigth*3+60+'px':'0'}">
        <view class="items" id="the-id">
          <!-- <view class="title">按订单状态选择</view> -->
          <view class="gridBtn">
            <u-button :type="orderStatesSelected(item)?'warning':'default'" @click="selectOrderStates(item)"
                      v-for="(item,index) in orderStatusList" :key="index" shape="circle"
                      :hair-line="false">{{item.text}}</u-button>
          </view>
        </view>
        <view class="items">
          <view class="title date-select">
            <text>按时间选择</text>
            <view class="date-type">
              <u-radio-group v-model="params.dateType" @change="radioGroupChange">
                <u-radio :name="3">配送</u-radio>
                <u-radio :name="1">下单</u-radio>
              </u-radio-group>
            </view>
          </view>
          <view class="gridBtn">
            <u-button :type="params.date===item.value?'warning':'default'"
                      @click="params.date=params.date==item.value?'':item.value"
                      v-for="(item,index) in orderDateList" :key="index" shape="circle"
                      :hair-line="false">{{item.text}}</u-button>
          </view>
          <view class="u-flex u-col-center u-row-between u-m-t-22">
            <input disabled @click="showTimeSelect(1)" v-model="params.beginDate" class="inputDate"
                   placeholder="起始时间" />
            <text>—</text>
            <input disabled @click="showTimeSelect(2)" v-model="params.endDate" class="inputDate"
                   placeholder="结束时间" />
          </view>
        </view>
        <view class="items">
          <view class="title">按评分选择</view>
          <view class="gridBtn">
            <u-button :type="params.totalScore===item.value?'warning':'default'"
                      @click="params.totalScore = item.value" v-for="(item,index) in orderScoreList" :key="index"
                      shape="circle" :hair-line="false">{{item.text}}</u-button>
          </view>
        </view>

        <view class="u-flex u-col-center u-row-between u-m-t-32">
          <u-button shape="circle" :hair-line="false" class="u-flex-1 u-m-l-10 u-m-r-10"
                    @click="reset">重置</u-button>
          <u-button shape="circle" type="warning" :hair-line="false" class="u-flex-1 u-m-l-10 u-m-r-10"
                    @click="searchFun">搜索</u-button>
        </view>

      </view>
      <view class="list">
        <navigator
            :url="userPinia.isLoginType==4?item.orderType!=11?'/subpackage/order/detail?orderId='+item.orderId:'/subpackage/order/rescueDetail?orderId='+ item.orderId:'/subpackage/order/detail?orderId='+item.orderId"
            hover-class="none" v-for="(item,index) in list" :key="index">
          <view class="items box-shadow u-p-b-16" v-if="item.orderType!=11">
            <view class="u-flex u-col-center u-row-between">
              <view class=" u-col-top" style="max-width: 78%;">
                <view class="u-line-1 u-font-32 fw-middel">{{item.beeperName}}</view>
                <view class="u-font-md u-m-t-6 color-gary-xs">{{item.createDate}}</view>
              </view>
              <view class="u-text-right">
                <block v-if="item.orderType ==3 && item.timingState ==1">
                  <view class="u-font-md u-m-b-12">计时中</view>
                </block>
                <block v-else-if="item.orderState == 13">
                  <view class="u-font-md u-m-b-12">已回收</view>
                </block>
                <block v-else-if="item.orderType ==3 && item.timingState ==2">
                  <view class="u-font-md u-m-b-12">计时结束</view>
                </block>
                <block v-else-if="item.orderState == 10 && item.timingState ==1">
                  <view class="u-font-md u-m-b-12 color-red">计时中</view>
                </block>
                <block v-else-if="item.orderState == 10 && item.timingState ==2">
                  <view class="u-font-md u-m-b-12 color-red">待回收</view>
                </block>
                <!-- <block v-else-if="item.orderState == 10">
                  <view class="u-font-md u-m-b-12 color-red">已到达</view>
                </block> -->

                <block v-else-if="item.errorState!=0">
                  <view class="u-font-md u-m-b-12 color-red">{{indexEnum.errorState[item.errorState]}}
                  </view>
                </block>
                <block v-else>
                  <view class="u-font-md u-m-b-12">{{indexEnum.orderStateFillter[item.orderState]}}
                  </view>
                </block>
                <u-tag :text="indexEnum.payStateFillter[item.payState]" type="success"
                       border-color="transparent" />
              </view>
            </view>

            <view class="u-flex u-col-center u-m-t-28">
              <scroll-view scroll-x class="u-flex-1  u-m-r-18 scroll"
                           style="white-space: nowrap;overflow: hidden;">
                <view class="inline-block item" v-for="(items,indexs) in item.goodsList" :key="indexs">
                  <!-- <image mode="widthFix" :src="items.images" style="object-fit: cover;"></image> -->
                  <u-image width="100%" height="110rpx" :src="items.images"></u-image>
                  <view class=" u-text-center u-font-md u-line-1 u-m-t-6">{{items.name}}</view>
                </view>
              </scroll-view>
              <view class="u-text-center u-p-t-18" style="align-self: flex-start;">
                <view class="u-font-lg">￥{{item.realAmount}}</view>
                <view class="u-font-md">共{{item.goodsList.length}}件</view>
              </view>
            </view>
            <view class="form" v-if="item.orderAttrs.length">
              <view class="form-item" v-for="(item2,index2) in item.orderAttrs" :key="index2">
                <block v-if="item2.fieldType!=4&&item2.fieldType!=5&&item2.fieldType!=8">
                  <view class="label">
                    {{item2.attrName}}：
                  </view>
                  <view class="value">
                    {{item2.value}}
                  </view>
                </block>
                <block v-if="item2.fieldType==4">
                  <view class="form-img-wrapper">
                    <view class="label" style="padding-bottom: 10rpx;width: 100%;">
                      {{item2.attrName}}：
                    </view>
                    <view class="img-wrapper" v-for="(item3,index3) in item2.value" :key="index3">
                      <image mode="aspectFill" :src="item3"
                             @click.stop="previewImg(item2.value,item3)">
                      </image>
                    </view>
                  </view>
                </block>
                <block v-if="item2.fieldType==5">
                  <view class="form-video-wrapper" @click.stop="">
                    <view class="label" style="padding-bottom: 10rpx;">
                      {{item2.attrName}}：
                    </view>
                    <video v-if="item2.value" controls show-play-btn id="video" objectFit='cover'
                           :src="item2.value">
                    </video>
                  </view>
                </block>
                <block v-if="item2.fieldType==8">
                  <view class="label">
                    {{item2.attrName}}：
                  </view>
                  <view v-if="item2.value" class="value volume-wrapper"
                        @click.stop="playAudio(item2)">
                    <view v-if="!item2.isPlay" style="color: #FD8008;">
                      播放
                      <u-icon name="volume-fill" />
                    </view>
                    <view wx:else style="color: red;">
                      播放中
                      <u-icon name="volume-fill" />
                    </view>
                  </view>
                </block>

              </view>

            </view>

          <!--  <view class="color u-font-24 u-m-t-18">
              <view v-if="item.customerName" class="u-m-b-4">患者姓名: {{item.customerName}}</view>
            </view> -->
            <view class="color u-font-24 u-m-t-18">
              <view v-if="item.beeperName" class="u-m-b-4">店铺: {{item.businessName}}</view>
            </view>

            <view class="color u-font-24 u-m-t-18">
              <view v-if="item.beeperName&&item.earliestTime&&item.serviceMode!==1" class="u-m-b-4">
                期望送达时间: <span class="exp-time">{{getOptimizeDateTwo(item.earliestTime)}}</span></view>
            </view>
            <view class="u-flex order-operation"
                  v-if="item.orderType!==3&&item.orderState>=10&&item.orderState<=12">
              <u-button size="medium"
                        @click="handleOrder(item,index)">{{indexEnum.orderOperationFillter[item.orderState]}}</u-button>
              <u-button v-if="item.orderState!==12&&item.orderState!==20" style="margin-left: 14rpx;"
                        type="warning" size="medium" @click="handleOrder(item,index,true)">一键完成</u-button>
            </view>

          </view>
          <view class="items box-shadow u-p-b-16" v-else>
            <view class="u-flex u-col-center u-row-between">
              <view class=" u-col-top" style="max-width: 78%;">
                <view class="u-line-1 u-font-32 fw-middel">{{item.beeperName}}</view>
                <view class="u-font-md u-m-t-6 color-gary-xs">{{item.createDate}}</view>
              </view>
              <view class="u-text-right">
                <block>
                  <view class="u-font-md u-m-b-12">{{indexEnum.orderStateFillter[item.orderState]}}
                  </view>
                </block>
              </view>
            </view>
			<view style="margin:8rpx 0">
				{{item.address}}
			</view>
            <image style="height: 400rpx;" v-if="item.siteUrl" :src="item.siteUrl || ''" mode="aspectFit"
                   @click.stop="showBigimg(item.siteUrl)"></image>
            <view class="u-flex order-operation">
              <u-button type="warning" size="medium"
                        @click="rescueDetail(item,index,true)">救援任务</u-button>
            </view>
          </view>
        </navigator>
      </view>

      <view class="exportBtn" v-if="userPinia.isLoginType!=0 && list.length!=0">
        <u-button type="warning" plain @click="exportOrder()"><u-icon name="download"></u-icon></u-button>

      </view>

      <view class="kong u-flex u-col-center u-row-center" v-if="userPinia.isLoginType==0">
        <u-empty mode="permission" text="登录后查看订单">
          <template #bottom>
            <button class="u-reset-button loginBtn" @click="tologin">登录</button>
          </template>
        </u-empty>

      </view>
      <block v-else>
        <view v-if="list.length===0" class="kong u-flex u-col-center u-row-center">
          <u-empty mode="order"></u-empty>
        </view>
      </block>


      <u-picker mode='time' :default-time="defalutTime" v-model='start_Time' :start-year="lastYear"
                :end-year="params.endDate.startsWith(lastYear)?lastYear:year" @confirm="startConfirm"></u-picker>
      <u-picker mode='time' :default-time="defalutTime" v-model='end_Time'
                :start-year="params.beginDate.startsWith(year)?year:lastYear" :end-year="year"
                @confirm="endConfirm"></u-picker>
      <u-mask :show="show" z-index="1" @click="show = false"></u-mask>


    </view>
    <tarBar></tarBar>
  </view>
</template>

<script setup lang="ts">
import userSotre from '@/store/user';
import { computed, onMounted, reactive, ref, unref } from "vue";
import { onReachBottom, onPullDownRefresh, onShow, onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import orderApi from '@/api/order';
import orderHooks from '@/hooks/order';
import { formatFormList, clearAudioFn } from "@/hooks"
import indexEnum from '@/enum/index';
import { getOptimizeDateTwo } from "@/utils"
const innerAudioContext = uni.createInnerAudioContext()
const userPinia = userSotre()

const start_Time = ref(false)
const end_Time = ref(false)
const heigth = ref('')
const search = ref()
const date = new Date()
const year = date.getFullYear()
const lastYear = year - 1
const month = date.getMonth() + 1
const day = date.getDate()
const nowDate = year + "-" + month + "-" + day
const lastDate = ref(lastYear + "-" + month + "-" + day)
const defalutTime = ref(nowDate)
// const NOW_DATE =

let params = reactive({
  groupValue: "",//搜索
  pageNo: 1,
  pageSize: 10,
  totalPage: 1,
  orderStates: userPinia.userRole == 3 ? [] : [5, 10, 11, 12],//订单状态
  date: 3,//时间选择
  totalScore: '',//按评分选择
  beginDate: '',//开始时间
  endDate: '',//结束时间
  dateType: userPinia.userRole == 3 ? 1 : 3,
})
const show = ref(false)
const list = ref([])
const orderStatusList = orderHooks.getOrderStatusList()
const orderDateList = orderHooks.getOrderDateList()
const orderScoreList = orderHooks.orderScoreList()

const back = () => {
  uni.navigateTo({
    url: '/subpackage/my/login/login'
  })
}

//导出订单数据
const exportOrder = (e) => {
  console.log(params.orderStates,"params.orderStatesparams.orderStates")
  orderApi.exportOrderList({
    orderNo: params.groupValue,
    orderStates: params.orderStates.toString(),
    dateType: params.dateType,
    date: params.date,
    beginDate:params.beginDate,
    endDate:params.endDate
  }).then(resa => {
    uni.showLoading({
      title: '下载中'
    })
    uni.downloadFile({
      url: resa.data,
      success: resb => {
        const fileManager = uni.getFileSystemManager()
        fileManager.saveFile({
          tempFilePath: resb.tempFilePath,
          success: (resc) => {
            uni.hideLoading()
            uni.openDocument({
              filePath: resc.savedFilePath,
              showMenu: true,
              fileType: 'xlsx'
            })
          }
        })
      }
    })
  }).catch(err => {

  })
}




const getList = (type) => {
  let cond = { ...params }
  if (cond.date) {
    Object.assign(cond, { beginDate: "", endDate: "" })
  }
  cond.orderStates = cond.orderStates.toString()
  orderApi.getOrderList(cond).then(res => {
    const onePage = params.pageNo === 1 ? true : false
    const { data } = res
    list.value = onePage ? data.list : list.value.concat(data.list)
    params.totalPage = data.totalPage
    list.value.forEach(item => {
      if (item.orderAttrs && item.orderAttrs.length) {
        item.orderAttrs = formatFormList(item.orderAttrs)
      }
    })
    stopAudio()
    switch (type) {
      case 'reset':
        uni.showToast({
          title: '已刷新...'
        })
        uni.stopPullDownRefresh()
        break;
    }
    if (onePage) {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    }
  })
}

function tologin() {
  uni.navigateTo({
    url: '/subpackage/my/login/login'
  })
}

const searchFun = () => {
  params.pageNo = 1
  getList()
  show.value = false
}

const selectOrderStates = (val) => {
  const index = params.orderStates.findIndex(item => item == val.value)
  if (index == -1) {
    params.orderStates.push(val.value)
  } else {
    params.orderStates.splice(index, 1)
  }
}
const orderStatesSelected = (val) => {
  return params.orderStates.some(item => item == val.value)
}
const reset = () => {
  Object.assign(params, {
    groupValue: "",//搜索
    pageNo: 1,
    pageSize: 10,
    totalPage: 1,
    orderStates: userPinia.userRole == 3 ? [1] : [5, 10, 11, 12],//订单状态
    date: 3,//时间选择
    totalScore: '',//按评分选择
    beginDate: '',//开始时间
    endDate: '',//结束时间
    dateType: userPinia.userRole == 3 ? 1 : 3,
  })
  list.value = []
}

const startConfirm = (e) => {
  params.beginDate = `${e.year}-${e.month}-${e.day}`
  params.date = ""
}
const endConfirm = (e) => {
  params.endDate = `${e.year}-${e.month}-${e.day}`
  params.date = ""
}

const searchChange = (e) => {
  list.value = []
  params.pageNo = 1
  getList()
}

// 显示时间
const showTimeSelect = (type) => {
  const { beginDate, endDate } = params
  if (type == 1) {
    defalutTime.value = beginDate ? beginDate : nowDate
    start_Time.value = true
  } else {
    defalutTime.value = endDate ? endDate : nowDate
    end_Time.value = true
  }
}

//查看大图
const showBigimg = (url) => {
  uni.previewImage({
    current: 0, //预览图片的下标
    urls: [url] //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
  })
}


// 操作订单
const handleOrder = async (item, index, finish) => {
  let { orderState, orderId } = item
  let msg = ""
  finish && (orderState = 12)
  switch (orderState) {
    case 10:
      msg = "出发"
      orderState = 11
      break
    case 11:
      msg = "到达"
      orderState = 12
      break
    case 12:
      msg = "完成"
      orderState = 20
      break
  }
  const { confirm } = await uni.showModal({
    title: "确认操作",
    content: `是否${msg}`
  })
  if (!confirm) return
  await orderApi.orderOperate({ id: orderId, state: orderState })
  await uni.showToast({
    title: "操作成功"
  })
  list.value[index].orderState = orderState
}

// 预览图片
const previewImg = (list, url) => {
  uni.previewImage({
    urls: list,
    current: url
  })
}

//救援详情
const rescueDetail = (item) => {
  if (userPinia.isLoginType == 3) {
    uni.showModal({
      title: "提示",
      content: `商家无权限查看急救详情`
    })
    return
  }
  uni.navigateTo({
    url: "/subpackage/order/rescueDetail?orderId=" + item.orderId
  })
}

// 播放录音
const playAudio = (target) => {
  let isPlay = target.isPlay
  stopAudio()
  if (!isPlay) {
    innerAudioContext.src = target.value
    innerAudioContext.play()
  } else {
    return
  }
  innerAudioContext.onPlay(() => {
    target.isPlay = true
  })
  innerAudioContext.onEnded(() => {
    target.isPlay = false
  })

}
// 停止播放
const stopAudio = () => {
  clearAudioFn(innerAudioContext)
  unref(list).find(item => {
    if (item.orderAttrs.length) {
      return item.orderAttrs.find(item2 => {
        if (item2.fieldType == 8 && item2.isPlay) {
          item2.isPlay = false
          return true
        }

      })
    }
  })
}


onMounted(() => {
  uni.createSelectorQuery().select('#the-id').boundingClientRect(function (rect) {
    heigth.value = rect.height
  }).exec()
})
onLoad(() => {
  uni.$on('setType', (res) => {
    list.value.find(item => {
      if (item.orderId == res) {
        item.orderState = 20
      }
    })
  })
  uni.$on('errorState', (obj) => {
    list.value.find(item => {
      if (item.orderId == obj.id) {
        item.errorState = obj.type
      }
    })
  })
  uni.$on('modifyOrderState', (res) => {
    list.value.find(item => {
      if (item.orderId == res.id) {
        item.orderState = res.state
      }
    })
  })
  uni.$on("cancelTakeOrder", orderId => {
    const res = list.value.findIndex(item => item.id == orderId)
    res && list.value.splice(index, 1)
  })
  uni.$on('getOrderList', () => {
    getList()
  })
})
onShow(() => {
  if (userPinia.isLoginType != 0) {
    getList()
  }
})
onReachBottom(() => {
  const { pageNo, totalPage } = params
  if (pageNo >= totalPage) return
  params.pageNo++
  getList()
})
onPullDownRefresh(() => {
  if (userPinia.isLoginType != 0) {
    params.pageNo = 1
    list.value = []
    getList('reset')
  }

})
onHide(() => {
  stopAudio()
})
onUnload(() => {
  stopAudio()
})
</script>

<style lang="scss" scoped>
.color {
  color: #706f6f;
}

.exportBtn {
  width: 100rpx;
  height: 100rpx;
  z-index: 99;
  position: fixed;
  right: 40rpx;
  bottom: 150rpx;
}

.list {
  .items {
    background-color: white;
    margin: 24upx;
    border-radius: 15upx;
    padding: 18upx 24upx;

    .order-operation {
      justify-content: flex-end;

      :deep(.u-btn) {
        // :deep(button){
        height: 58rpx;
        padding: 0 30rpx;
        // }

      }
    }

    .form {
      background-color: #f0f0f0;
      box-sizing: border-box;
      padding: 20rpx;
      border-radius: 20rpx;

      .form-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        font-size: 29rpx;

        .label {
          width: 40%;
          color: #696969;
        }

        .value {
          width: 60%;
          text-align: end;
        }

        .volume-wrapper {
          color: #FD8008;
          display: flex;
          align-items: center;
          justify-content: flex-end;

          .is-active__volume {
            color: red !important;
          }
        }

        .form-img-wrapper {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          font-size: 30rpx;

          .img-wrapper {
            width: 140rpx;
            height: 140rpx;
            border-radius: 15rpx;
            flex-shrink: 0;
            margin: 4rpx 10rpx 10rpx 0;

            image {
              height: 100%;
              width: 100%;
            }
          }
        }

        .form-video-wrapper {
          width: 100%;

          video {
            margin: 0 auto;
            display: block;
            width: 100%;
            border-radius: 10rpx;
          }
        }
      }

    }

    .scroll {
      .item {
        width: 140upx;
        margin-right: 25upx;

        // >image{
        // 	max-width: 100upx;
        // 	height: 100upx;

        // }
      }
    }
  }
}

.seleBottom {
  // height: 0upx;
  overflow: hidden;
  transition: all .38s;
  background-color: #f5f5f5;
  // padding: 10upx 0 28upx;
  border-radius: 0 0 28upx 28upx;

  .items {
    padding: 10upx 26upx;

    .date-select {
      display: flex;
      align-items: center;

      .date-type {
        transform: translateY(2upx);
        font-weight: normal;
        margin-left: 20upx;
      }
    }

    .title {
      font-size: 32upx;
      font-weight: 600;
      padding-bottom: 18upx;
    }

    .gridBtn {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-column-gap: 24upx;
      grid-row-gap: 18upx;

      :deep(.u-size-default) {
        line-height: 60upx !important;
        font-size: 26upx;
        height: 60upx !important;
      }
    }

    .inputDate {
      text-align: center;
      background-color: #fff;
      height: 2.3em;
      border-radius: 26upx;
      border: 1upx solid #c0c4cc;
    }
  }
}

.kong {
  width: 100vw;
  height: 70vh;
}

.loginBtn {
  background-image: linear-gradient(to top, #FEBF00, #FFCE05);
  line-height: 2.4em;
  width: 180upx;
}

.search {
  background-color: #ffc300;
  width: 100%;
  position: sticky;
  left: 0;
  top: 0;
  z-index: 10;

  .ri_btn {
    image {
      width: 40upx;
      height: 40upx;
    }

    text {
      font-size: 28upx;
      margin-left: 10upx;
    }
  }
}

.exp-time {
  font-weight: 900;
  color: red;
  font-size: 32rpx;
  display: inline-block;
  transform: translateY(3rpx)
}
</style>
